import time

import cv2
import mss
import numpy as np


def take_full_screenshot():
    # 创建一个 mss 实例
    with mss.mss() as sct:
        # 获取整个屏幕的信息
        monitor = sct.monitors[1]  # 这里的 monitors[1] 表示整个屏幕，monitors[0] 通常是包含所有显示器的虚拟屏幕
        sct_img = sct.grab(monitor)
        screen_img = cv2.cvtColor(np.array(sct_img), cv2.COLOR_RGBA2RGB)
        # 转换图像为灰色
        screen_img_gray = cv2.cvtColor(np.array(screen_img), cv2.COLOR_BGR2GRAY)
        return screen_img, screen_img_gray

def find_img_xy(screen_img_gray, target_img, thresh=0.8):
    result_xy = []
    # 模板匹配
    result = cv2.matchTemplate(screen_img_gray, target_img, cv2.TM_CCOEFF_NORMED)
    locations = np.where(result >= thresh)
    locations = list(zip(*locations[::-1]))

    if len(locations) > 0:
        height = target_img.shape[0]
        width = target_img.shape[1]
        x = int(locations[0][0]) + int(width / 2)
        y = int(locations[0][1]) + int(height / 2)
        result_xy = [x, y]
    return result_xy

def read_gray_img(path):
    return cv2.imread(path, cv2.IMREAD_GRAYSCALE)

def execute_until_true(anonymous_func, n, sleep_time=0.3):
    count = 0
    result = False
    while count < n:
        result = anonymous_func()
        if result:
            break
        else:
            time.sleep(sleep_time)
            print(f'方法：{anonymous_func.__name__}执行失败，重试第{count + 1}次')
            count += 1
    time.sleep(sleep_time)
    return result

